<template>
  <div class="main-container">
    <div class="main-section" @scroll="handleScroll" ref="mainSection">
      <div id="section1" class="section">
        <h2 style="margin-bottom: 0px; color: #2196f3;">经纪人合同管理</h2>
        <div class="button-container">
          <el-button type="primary" @click="handleNewContract">添加</el-button>
        </div>
        <el-table :data="ContractData" stripe style="width: 100%; height: auto;" :cell-padding="0">
          <el-table-column prop="id" label="合同编号"></el-table-column>
          <el-table-column prop="contractName" label="合同标题"></el-table-column>
          <el-table-column prop="startDate" label="起始日期"></el-table-column>
          <el-table-column prop="endDate" label="终止日期"></el-table-column>
          <el-table-column label="状态">
            <template v-slot="scope">
              {{ mapContractStatus(scope.row.contractStatue) }}
            </template>
          </el-table-column>
          <el-table-column prop="contractLink" label="文件链接">
            <template v-slot="scope">
              <a :href="scope.row.link" target="_blank">{{ scope.row.contractLink }}</a>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template #default="scope">
              <el-button type="primary" size="small" :icon="Edit" @click="handleEditContract(scope.row)">修改</el-button>
              <el-button type="danger" size="small" :icon="Delete"
                @click="handleDeleteContract(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div id="section2" class="section" style="height: fit-content; width:95%; margin-bottom: 50px;">
        <h2 style="margin-bottom: 0px; color: #2196f3;">艺人指派管理</h2>
        <div class="button-container">
          <el-button type="primary" @click="openAddArtistDialog">添加</el-button>
        </div>
        <div style="display: flex; flex-direction: row; margin-top: 30px">
          <el-table :data="assignedArtists" stripe style="width: 100%;">
            <el-table-column prop="name" label="艺人姓名"></el-table-column>
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button type="danger" size="small" @click="removeArtist(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>

    <div class="sidebar">
      <ul>
        <li @click="scrollToSection('section1')" :class="{ active: currentSection === 'section1' }">经纪人合同管理</li>
        <li @click="scrollToSection('section2')" :class="{ active: currentSection === 'section2' }">艺人指派管理</li>
      </ul>
    </div>
  </div>

  <!--contract pop-up windows-->
  <el-dialog title="创建新合同" v-model="newContract" :visible.sync="newContract" width="30%" :before-close="handleClose">
    <el-form :model="contractForm" :rules="contractRules" ref="newContractFormRef" label-width="100px" class="demo-ruleForm">
      <el-form-item label="合同标题" prop="contractName">
        <el-input v-model="contractForm.contractName"></el-input>
      </el-form-item>
      <el-form-item label="起始时间" prop="startDate">
        <el-input v-model="contractForm.startDate"></el-input>
      </el-form-item>
      <el-form-item label="结束时间" prop="endDate">
        <el-input v-model="contractForm.endDate"></el-input>
      </el-form-item>
      <el-form-item label="合同状态">
        <el-select v-model="contractForm.contractStatue" placeholder="请选择活动状态">
          <el-option label="未确认" value="PENDING"></el-option>
          <el-option label="有效" value="ACTIVE"></el-option>
          <el-option label="已结束" value="TERMINATED"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="文件链接" prop="contractLink">
        <el-input v-model="contractForm.contractLink"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitContractForm('newContractFormRef')">立即创建</el-button>
        <el-button @click="resetForm('newContractFormRef')">重置</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
  <!--修改合同-->
  <el-dialog title="修改合同信息" v-model="editContract" :visible.sync="editContract" width="30%" :before-close="handleClose">
    <el-form :model="contractForm" :rules="contractRules" ref="newContractFormRef" label-width="100px"
      class="demo-ruleForm">
      <el-form-item label="合同标题" prop="contractName">
        <el-input v-model="contractForm.contractName"></el-input>
      </el-form-item>
      <el-form-item label="起始时间" prop="startDate">
        <el-input v-model="contractForm.startDate"></el-input>
      </el-form-item>
      <el-form-item label="结束时间" prop="endDate">
        <el-input v-model="contractForm.endDate"></el-input>
      </el-form-item>
      <el-form-item label="合同状态">
        <el-select v-model="contractForm.contractStatue" placeholder="请选择活动状态">
          <el-option label="未确认" value="PENDING"></el-option>
          <el-option label="有效" value="ACTIVE"></el-option>
          <el-option label="已结束" value="TERMINATED"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="文件链接" prop="contractLink">
        <el-input v-model="contractForm.contractLink"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitContractForm('newContractFormRef')">立即修改</el-button>
        <el-button @click="resetForm('newContractFormRef')">重置</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!--modify responsible artist pop-up window-->
  <!--add responsible artist-->
  <el-dialog title="添加艺人" v-model="addDialogVisible" width="40%">
    <el-table :data="availableArtists" stripe style="width: 100%;">
      <el-table-column prop="name" label="艺人姓名"></el-table-column>
      <el-table-column label="操作" width="120">
        <template #default="scope">
          <el-button type="primary" size="small" @click="assignArtist(scope.row.id)">指派</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>

  <!--delete responsible artist-->
  <el-dialog title="删除艺人" v-model="removeDialogVisible" width="30%">
    <el-table :data="assignedArtists" stripe style="width: 100%;">
      <el-table-column prop="name" label="艺人姓名"></el-table-column>
      <el-table-column label="操作" width="120">
        <template #default="scope">
          <el-button type="danger" size="small" @click="removeArtist()">移除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>

  <!--confirm delete responsible artist-->
   <el-dialog v-model="confirmRemoveDialogVisible" title="确认删除" width="30%">
    <span>确定要移除艺人 {{ selectedArtist?.name }} 吗？</span>
    <template #footer>
      <el-button @click="confirmRemoveDialogVisible = false">取消</el-button>
      <el-button type="danger" @click="confirmRemoveArtist">确定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import request from '@/utils/request'
import {ElMessage } from 'element-plus'

export default {
  data() {
    return {
      value: [0, 132],
      currentSection: 'section1',
      tableData: [], // 保留但清空原有数据
      ruleForm: {},  // 保留但清空原有数据

      //contract section
      ContractData: [], // 合同数据
      newContract: false,
      editContract: false,
      editContractID: -1,
      contractForm: {
        id: '',
        contractName: '',
        contractType: 'AGENT_CONTRACT',
        personId: this.currentAgentId,
        startDate:'',
        endDate: '',
        contractStatue: '',
        contractLink: ''
      },
      contractRules: {
        contractName: [
          { required: true, message: '请输入合同标题', trigger: 'change' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        startDate: [
          { type: 'date', required: true, message: '请输入日期', trigger: 'change' }
        ],
        endDate: [
          { type: 'date', required: true, message: '请输入日期', trigger: 'change' }
        ]
      },

      //responsible artist section
      assignedArtists: [],  // 当前经纪人管理的艺人
      availableArtists: [], // 所有可用的艺人
      addDialogVisible: false, // 添加艺人弹窗显示状态
      removeDialogVisible: false, // 删除艺人弹窗显示状态
      confirmRemoveDialogVisible: false, // 确认删除弹窗
      selectedArtist: null, // 当前选中的艺人
      currentAgentId: sessionStorage.getItem('userId') || 2, // 当前经纪人ID (TODO:实际项目中根据登录用户确定)
    };
  },
  methods: {
    /**
     * scroll section
     */
    handleScroll(event) {
      const mainSection = event.target;
      const sections = ['section1', 'section2']; 
      const containerMid = mainSection.clientHeight / 2;
      let closestSection = this.currentSection;
      let minDistance = Infinity;

      sections.forEach(section => {
        const rect = document.getElementById(section).getBoundingClientRect();
        const sectionMid = (rect.top + rect.bottom) / 2;
        const distance = Math.abs(sectionMid - containerMid);

        if (distance < minDistance) {
          minDistance = distance;
          closestSection = section;
        }
      });

      this.currentSection = closestSection;
    },
    scrollToSection(sectionId) {
      const section = document.getElementById(sectionId);
      section.scrollIntoView({ behavior: 'smooth' });
      this.currentSection = sectionId;
    },

    resetForm(formName) {
      this.$refs[formName].resetFields()

      // 重置滑动条状态
      this.value = [0, 132] // 恢复默认时间范围（12:00-23:00）

      // 清空时间字段（如需要）
      this.ruleForm.startime = ''
      this.ruleForm.endtime = ''
    },
    
    /**
     * Contract section begin
     */
    getContract() {
      request.get(`/getContract/AGENT_CONTRACT/${this.currentAgentId}`).then(res => {
        console.log(res)
        this.ContractData = res.data.data;
      });
    },

    mapContractStatus(status) {
      const statusMap = {
        'ACTIVE': '有效',
        'PENDING': '未确认',
        'TERMINATED': '终止'
      };
      return statusMap[status] || status; // 未匹配则返回原值
    },

    handleNewContract() {
      this.newContract = true;
      this.contractForm = {
        contractName: '',
        contractType: 'AGENT_CONTRACT',
        personId: this.currentAgentId,
        startDate:'',
        endDate: '',
        contractStatue: '',
        contractLink: ''
      };
    },

    handleEditContract(row) {
      this.editContractID = row.id; // 记录当前编辑的索引
      this.contractForm = {
        id: row.id,
        contractType: "AGENT_CONTRACT",
        personId: this.currentAgentId,
        contractName: row.contractName,
        startDate: row.startDate,
        endDate: row.endDate,
        contractStatue: row.contractStatue, // 使用原始状态值
        contractLink: row.contractLink
      };// 复制当前行数据到表单
      this.editContract = true; // 打开对话框
      // 重置表单校验状态
      // if (this.$refs.editFormRef) {
      //   this.$refs.editFormRef.resetFields()
      // }
    },

    handleDeleteContract(row) {
      this.$confirm('确定删除此合同吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request.delete(`/deleteContract/${row.id}`).then(res => {
          if (res.data.code === 200) {
            // 删除成功，刷新数据
            this.$message.success('删除成功');
            this.getContract()
          } else {
            ElMessage.error(res.data.msg || '删除合同失败')
          }
        }).catch(err => {
          console.error('删除合同失败:', err)
          this.$message.error('删除合同失败')
        })
      }).catch(() => { });
    },
    
    submitContractForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.editContract === true) {
            request.put(`/updateContract/${this.editContractID}`, this.contractForm).then(res => {
              if (res.data.code === 200) {
                // 更新成功，刷新数据
                this.$message.success('更新成功')
                this.getContract()
                // 关闭对话框
                this.editContract = false
                this.editContractID == -1
                this.contractForm = {
                  contractName: '',
                  startDate: '',
                  endDate: '',
                  contractStatue: '',
                  contractLink: ''
                }
              } else {
                this.$message.error(res.data.msg || '修改合同失败')
              }
            }).catch(err => {
              console.error('更新合同失败:', err)
              this.$message.error('更新合同失败')
            })
          }
          else if (this.newContract === true) {
            request.post('/addContract', this.contractForm).then(res => {
              if (res.data.code === 200) {
                // 添加成功，刷新数据
                this.$message.success('添加合同成功')
                this.getContract()
                // 关闭对话框
                this.newContract = false
              }
              else {
                this.$message.error('添加合同失败')
              }
            }).catch(err => {
              console.error('添加合同失败:', err)
              this.$message.error('添加合同失败')
            })
          }


        } else {
          console.log('提交失败!!');
          return false;
        }
      });
    },
    /**
     * Contract section end
     */

    /**
     * Assign section begin
     */
    //fetch artists currently managed by current agent
    fetchAssignedArtists() {
      let allAtrist=[];
      request.get('/getArtistInfo').then(res=>{
        if (res.data.code === 200){
          allAtrist=res.data.data;
        }else {
          ElMessage.error('获取所有艺人失败');
        }
      })
      request.get(`/getAgentWithArtists/${this.currentAgentId}`)
        .then(res => {
          const artistNames = res.data.data.artistNames || [];
          for(const key in allAtrist){
            if(artistNames.includes(allAtrist[key].name)){
              this.assignedArtists.push({id:allAtrist[key].id,name:allAtrist[key].name});
            }
          }
        });
    },

    //fetch all available artists in the database
    fetchAvailableArtists() {
      request.get('/getArtistInfo')
        .then(res => {
          // 过滤掉已经指派的艺人
          const assignedNames = this.assignedArtists.map(a => a.id);
          this.availableArtists = res.data.data.filter(artist => 
            !assignedNames.includes(artist.id)
          );
        });
    },

    openAddArtistDialog() {
      this.fetchAvailableArtists();
      this.addDialogVisible = true;
    },

    removeArtist(artist) {
      this.selectedArtist = {id:artist.id,name:artist.name};
      this.confirmRemoveDialogVisible = true;
    },

    //assigned artist to the agent
    assignArtist(artistID) {
      request.post(`/assignArtist/${this.currentAgentId}/${artistID}`).then(res => {
        if (res.data.code === 200) {
          this.$message.success('指派成功');
          this.assignedArtists=[];
          this.fetchAssignedArtists();
          this.addDialogVisible = false;
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },

    //comfirm to delete artist 
    confirmRemoveArtist() {
      request.delete(`/unassignArtist/${this.currentAgentId}/${this.selectedArtist.id}`).then(res => {
        if (res.data.code === 200) {
          this.$message.success('移除成功');
          this.assignedArtists=[]
          this.fetchAssignedArtists();
        } else {
          this.$message.error(res.data.msg);
        }
        this.confirmRemoveDialogVisible = false;
      });
    },
    /**
     * Assign section end
     */
  },

  mounted(){
    this.getContract();
    this.fetchAssignedArtists();
  }
};
</script>

<style scoped>
.main-container {
  display: flex;
  height: calc(100vh - 60px); /* 更好的视口高度管理 */
}

.main-section {
  flex: 1;
  overflow-y: auto;
  scrollbar-width: none;
  -ms-overflow-style: none;
}

.main-section::-webkit-scrollbar {
  display: none;
}

.section {
  min-height: 600px;
  padding: 20px;
  margin-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

#section2 {
  height: auto; /* 自适应高度 */
}

.sidebar {
  width: 200px;
  padding: 20px;
  background-color: #f9f9f9;
  border-left: 1px solid #e4e7ed;
}

.sidebar ul {
  list-style-type: none;
  padding: 0;
}

.sidebar li {
  cursor: pointer;
  margin: 15px 0;
  padding: 10px 15px;
  position: relative;
  transition: all 0.3s ease;
  border-radius: 4px;
  color: #606266;
}

.sidebar li:hover {
  background-color: #ecf5ff;
  color: #409eff;
  transform: translateX(5px);
}

.sidebar li.active {
  background-color: #409eff;
  color: white;
  font-weight: bold;
}

/*按钮样式*/
.button-container {
  display: flex;
  justify-content: flex-end;
  /* 将按钮对齐到容器的最右边 */
  margin-bottom: 10px;
  /* 可选：添加一些底部边距，以便按钮和表格之间有一些空间 */
}
</style>